const fs = require('fs');
const path = require('path');
const join = require('path').join;
const xml2js = require('xml2js');
const MongoClient = require('mongodb').MongoClient; //数据库
const server = require('./config/server'); //数据库配置文件
var collec = 'lonlat'; //数据库集合
var mongodb = 'mongodb://' + server.mongodb.user +
    ':' +
    server.mongodb.password +
    '@' + server.mongodb.host +
    ':' + server.mongodb.port +
    '/' +
    server.mongodb.database +
    '?authMechanism=' +
    server.mongodb.authMechanism +
    '&authSource=' +
    server.mongodb.authSource; //数据库地址

//获取国文件夹下的省kml路径
function getCountryKmlPath(startPath) {
    let countryKmlPaths = []; //返回值
    let countryResources = fs.readdirSync(startPath); //获取当前目录下的所有文件
    countryResources.forEach((countryResource, index) => {
        let countryResourcePath = join(startPath, countryResource);
        let countryResourceStats = fs.statSync(countryResourcePath);
        if (countryResourceStats.isFile() && path.extname(countryResourcePath) == '.kml') {
            countryKmlPaths.push(countryResourcePath); //判定是文件且文件后缀是'.td'
        }
    });
    return countryKmlPaths;
}
// console.log('getCountryKmlPath', getCountryKmlPath('./资料/中国坐标文件/'));

//获取省文件夹下面的市kml路径
function getProvKmlPath(startPath) {
    let provKmlPaths = []; //返回值
    let countryResources = fs.readdirSync(startPath); //获取国家目录下的所有文件
    countryResources.forEach(countryResource => {
        let countryResourcePath = join(startPath, countryResource); //拼接国家文件夹下资源路径
        let countryResourceStats = fs.statSync(countryResourcePath);
        if (countryResourceStats.isDirectory()) {
            let provResources = fs.readdirSync(countryResourcePath); //获取省文件夹下面的文件
            provResources.forEach((provResource, index) => {
                let provResourcePath = join(countryResourcePath, provResource); //拼接省份文件夹下面的文件路径
                let provResourceStats = fs.statSync(provResourcePath);
                if (provResourceStats.isFile() && path.extname(provResourcePath) == '.kml') {
                    let provName = provResource.replace('.kml', '');
                    provKmlPaths.push(provResourcePath);
                }
            })
        };
    }); //循环判定是是否是文件夹
    return provKmlPaths;
}
// console.log('getProvKmlPath', getProvKmlPath('./资料/中国坐标文件/'));

//获取市文件夹下面的区kml路径
function getCityKmlPath(startPath) {
    let cityKmlPaths = []; //返回值
    let countryResources = fs.readdirSync(startPath); //获取国家目录下的所有文件
    countryResources.forEach(countryResource => {
        let countryResourcePath = join(startPath, countryResource); //拼接国家文件夹下资源路径
        let countryResourceStats = fs.statSync(countryResourcePath);
        if (countryResourceStats.isDirectory()) {
            let provResources = fs.readdirSync(countryResourcePath); //获取省文件夹下面的文件
            provResources.forEach((provResource, index) => {
                let provResourcePath = join(countryResourcePath, provResource); //拼接省份文件夹下面的文件路径
                let provResourceStats = fs.statSync(provResourcePath);
                if (provResourceStats.isDirectory()) {
                    //市
                    let cityResources = fs.readdirSync(provResourcePath); //获取市文件夹下面的文件
                    cityResources.forEach((cityResource, index) => {
                        let cityResourcePath = join(provResourcePath, cityResource); //拼接市份文件夹下面的文件路径
                        let cityResourceStats = fs.statSync(cityResourcePath);
                        if (cityResourceStats.isFile() && path.extname(cityResourcePath) == '.kml') {
                            let cityName = cityResource.replace('.kml', '');
                            cityKmlPaths.push(cityResourcePath);
                        }
                    })
                }
            })
        };
    });
    return cityKmlPaths;
}
// console.log('getCityKmlPath', getCityKmlPath('./资料/中国坐标文件/'));

//获取区文件夹下面的乡村或者其他kml路径
function getDistKmlPath(startPath) {
    let distKmlPaths = []; //返回值
    let countryResources = fs.readdirSync(startPath); //获取国家目录下的所有文件
    countryResources.forEach(countryResource => {
        let countryResourcePath = join(startPath, countryResource); //拼接国家文件夹下资源路径
        let countryResourceStats = fs.statSync(countryResourcePath);
        if (countryResourceStats.isDirectory()) {
            let provResources = fs.readdirSync(countryResourcePath); //获取省文件夹下面的文件
            provResources.forEach((provResource, index) => {
                let provResourcePath = join(countryResourcePath, provResource); //拼接省份文件夹下面的文件路径
                let provResourceStats = fs.statSync(provResourcePath);
                if (provResourceStats.isDirectory()) {
                    let cityResources = fs.readdirSync(provResourcePath); //获取市文件夹下面的文件
                    cityResources.forEach((cityResource, index) => {
                        let cityResourcePath = join(provResourcePath, cityResource); //拼接市份文件夹下面的文件路径
                        let cityResourceStats = fs.statSync(cityResourcePath);
                        if (cityResourceStats.isDirectory()) {
                            //区
                            let distResources = fs.readdirSync(cityResourcePath); //获取市文件夹下面的文件
                            distResources.forEach((distResource, index) => {
                                let distResourcePath = join(cityResourcePath, distResource); //拼接市份文件夹下面的文件路径
                                let distResourceStats = fs.statSync(distResourcePath);
                                if (distResourceStats.isFile() && path.extname(distResourcePath) == '.kml') {
                                    let distName = distResource.replace('.kml', '');
                                    distKmlPaths.push(distResourcePath);
                                }
                            })

                        }
                    })
                }
            })
        };
    });
    return distKmlPaths;
}
// console.log('getDistKmlPath', getDistKmlPath('./资料/中国坐标文件/'));

//把路径下的kml文件内容(名称和经纬度)转换成json
function kmlToJson(kmlPaths) {
    let jsonArr = []; //返回值
    kmlPaths.forEach((kmlPath, index) => {
        let jsonObj = {}; //返回单条数据
        jsonObj.name = '';
        jsonObj.children = [];
        let cutSlantLine = kmlPath; //获取单条数据地址
        let cutSlantLineIndex = cutSlantLine.lastIndexOf("\\");
        cutSlantLine = cutSlantLine.substring(cutSlantLineIndex + 1, cutSlantLine.length); //获取最后一个\后面的数据
        let kmlName = cutSlantLine.replace('.kml', ''); //去掉数据的'.kml',返回kml名
        jsonObj.name = kmlName; //把名称添加到返回值
        let data = fs.readFileSync(kmlPath, 'utf-8'); //同步读取文件
        let parser = new xml2js.Parser(); //利用xml2js把ml文件解析成json文件
        parser.parseString(data, function(err, json) {
            let originalDoc = json.kml.Document[0].Folder[0].Placemark; //获取省经纬度json原始数据
            originalDoc.forEach(doc => {
                let namelonLatObj = {}; //省名和经纬度
                let namelonLat = {}; //应纬度
                namelonLat.lon = doc.Point[0].coordinates[0].split(",")[0]; //经度
                namelonLat.lat = doc.Point[0].coordinates[0].split(",")[1]; //纬度
                namelonLatObj.name = doc.name.toString(); //名称
                namelonLatObj.point = namelonLat; //经纬度
                namelonLatObj.children = []; //子节点
                jsonObj.children.push(namelonLatObj); //把数据添加到返回值的子节点
            })
        });
        jsonArr.push(jsonObj);
    });
    return jsonArr;
}

//获取省份对应的经纬度
let countrys = kmlToJson(getCountryKmlPath('./资料/中国坐标文件/'));

//获取市对应的经纬度
let provs = kmlToJson(getProvKmlPath('./资料/中国坐标文件/'));

//获取区对应的经纬度
let citys = kmlToJson(getCityKmlPath('./资料/中国坐标文件/'));

//获取乡村和其他数据对应的经纬度
let dists = kmlToJson(getDistKmlPath('./资料/中国坐标文件/'));

//把市数据添加到省数据里面
countrys[0].children.forEach(countryProv => {
    let countryProvName = countryProv.name; //省名
    //循环获取的省数据
    provs.forEach(prov => {
        let provName = prov.name //获取省份名称
        let provChildren = prov.children //获取省份下面的子节点
        if (provName == countryProvName) {
            countryProv.children = provChildren; //把市数据加入指定省
        }
    });
});

//把区数据添加到市数据里面
countrys[0].children.forEach(countryProv => {
    let countryProvChildren = countryProv.children;
    countryProvChildren.forEach(countryProvCity => {
        let countryProvCityName = countryProvCity.name;
        //循环获取的市数据
        citys.forEach(city => {
            let cityName = city.name;
            let cityChildren = city.children;
            if (cityName == countryProvCityName) {
                countryProvCity.children = cityChildren; //把区数据加入指定市
            }
        })
    });
});
// console.log('countrys', JSON.stringify(countrys));

//把乡村和其他数据装进区里面
countrys[0].children.forEach(countryProv => {
    let countryProvChildren = countryProv.children;
    countryProvChildren.forEach(countryProvCity => {
        let countryProvCityChildren = countryProvCity.children;
        countryProvCityChildren.forEach(countryProvCityDist => {
            let countryProvCityDistName = countryProvCityDist.name;
            //循环获取的市数据
            dists.forEach(dist => {
                let distName = dist.name;
                let distChildren = dist.children;
                if (distName == countryProvCityDistName) {
                    countryProvCityDist.children = distChildren; //把乡镇和其他数据加入指定市
                }
            })
        })
    });
});
// console.log('countrys', JSON.stringify(countrys));

// 把全部数据插入mongodb数据库
countrys[0].children.forEach(prov => {
    MongoClient.connect(mongodb, {
        useNewUrlParser: true
    }, (err, client) => {
        let db = client.db(server.mongodb.database);
        let collection = db.collection(collec);
        collection.insertOne(prov, (err, doc) => {
            if (!err) {
                client.close();
            }
        });
    });
});